/**
 * 编写请求的统一代码
 * 
 * */

var express = require('express');
var db_mysql = require('./mysql.js');
const crypto = require('crypto');
const protoco = 'http://'
let host = '127.0.0.1'
var port = 3003;
var port1 = 3004;
const projectName = 'plantknow';
var os = require('os');
// 获取操作系统
var platform = os.platform();
console.log('操作系统为：', platform)
if(platform === 'linux') {
    host = '0.0.0.0'
    port1 = 3004
    port = 3003
}
var errorData = {
    status: 1,
    code: 200,
    msg: '错误信息'
}


/**
 * 获取16位的随机串
 * */
function strLen() {
    var str = '';
    for (var i = 0; i < 16; i++) {
        str += (Math.floor((Math.random() * 15) + 1)).toString(16);
    }
    return str;
}
// 十六位十进制的随机码
function strLenHex() {
    var str = '';
    for (var i = 0; i < 16; i++) {
        str += (Math.floor((Math.random() * 9))).toString(10);
    }
    return str;
}
/**
 * 加密
 * */
function addPWD(data, password) {
    // 加密的算法
    const algorithm = 'aes-192-cbc';
    // 使用aes192算法加密，加密的密码是st，创建一个cipher对象
    const cipher = crypto.createCipher(algorithm, password);
    //加密
    let crypted = cipher.update(data, 'utf-8', 'hex');
    // 返回加密后的数据的,final之后不能再update
    crypted += cipher.final('hex');
    return crypted;
}
/**
 * 解密
 * @param {String} data 解密数据
 * @param {String} password 解密的密码 
 * */
function enCodePWD(data, password) {
    // 加密的算法
    const algorithm = 'aes-192-cbc';
    // 使用aes192算法加密，加密的密码是st，创建一个cipher对象
    const decipher = crypto.createDecipher(algorithm, password);
    let decrypted = decipher.update(data, 'hex', 'utf-8');
    // 返回加密后的数据的,final之后不能再update
    decrypted += decipher.final('utf-8');
    return decrypted;
}
/**
 * 获取对应的时间时间格式
 * @param {Date} d 默认为当前时间  
 * */
// function timeFormat(d = new Date().getTime()) {
//     let d = new Date(d);
//     let Y = d.getFullYear();
//     let M = d.getMonth()
// }


let request = require("request");
let fs = require("fs");

class Util {
    /**
     * 下载网络图片
     * @param {object} opts 
     */
    static downImg(opts = {}, dirPath = '') {
        return new Promise((resolve, reject) => {
            request
            .get(opts)
            .on('response', (response) => {
                console.log("img type:", response.headers['content-type'])
            })
            .pipe(fs.createWriteStream(dirPath))
            .on("error", (e) => {
                console.log("pipe error", e)
                resolve('');
            })
            .on("finish", () => {
                console.log("finish");
                resolve("ok");
            })
            .on("close", () => {
                console.log("close");
            })

        })
    }
}
/**
 * 下载图片到本地
 * @param {Object} params 信息
 * */
async function downLoadImg(params) {
    try {
        let opts = {
            url: params.url,
            headers: {
                'Referer': params.hostName,
            }
        };
        let path = params.path;
        let r1 = await Util.downImg(opts, path);
        console.log(r1);
    } catch (e) {
        console.log(e);
    }
}

async function historyProduct(data, pageNum, pageSize) {
    // console.log('length0', data)
    
    if (data.length > 0) {
        let hisRes = []
        let productRes = [];
        data.forEach(item => {
            for (var i in hisRes) {
                if (hisRes[i].name === item.genusId) {
                    hisRes[i].value++;
                    return;
                }
            }
            hisRes.push({
                name: item.genusId,
                value: 1
            })
        })
        hisRes = hisRes.reduce((prev, cur, index, arr) => {
            for (var k in prev) {
                if (prev[k].value < cur.value) {
                    prev.splice(k, 0, cur)
                    return prev;
                }
            }
            prev.push(cur)
            return prev;
        }, [])
        if (hisRes.length > 3) {
            hisRes = hisRes.slice(0, 3);
        }
        let selSql = 'select * from botanys where genusId=? limit ?, ?'
        for(var k in hisRes) {
            let selArr = [hisRes[k].name, pageNum * pageSize, 4 - k]
            let result = await db_mysql.asyncSelect(selSql, selArr);
            productRes = [...productRes, ...result]
        }
        let num = 10 - productRes.length;
        let selProdSql = 'select * from botanys limit ?, ?';
        let selProdArr = [pageNum * num, num];
        let result1 = await db_mysql.asyncSelect(selProdSql, selProdArr)
        productRes = [...productRes, ...result1];
        // console.log('res', productRes)
        return productRes;
    } else {
        let selSql = 'select * from botanys limit ?, ?';
        let selArr = [pageNum * pageSize, pageSize];
        const result = await db_mysql.asyncSelect(selSql, selArr)
        return result;
    }
}

// 鉴定小程序是否需要token鉴定
function urlIndentify(url) {
    let urlArr = ['/history']
    for(var i in urlArr) {
        if(url.indexOf('/plantknow' + urlArr[i]) > -1) {
            return true;
        }
    }
    return false;
}


module.exports = {
    express,
    db_mysql,
    errorData,
    strLen,
    addPWD,
    enCodePWD,
    Util,
    host,
    port,
    port1,
    protoco,
    platform,
    downLoadImg,
    historyProduct,
    strLenHex,
    urlIndentify,
    projectName
}
